package controller;

import java.io.File;
import java.io.IOException;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;

public class MidiPlayer {
	
	private static MidiPlayer mInstance;
	
	private Sequence seq;
	private Sequencer seqr;
	
	
	
	static {
		mInstance = new MidiPlayer();
	}
	
	private MidiPlayer() {
		
	}
	
	
	public void playMidi(File midiFile) {
		if (seqr != null) {
			if (seqr.isRunning()) {
				seqr.stop();
			}
		}
		
		if (midiFile != null) {
			if (midiFile.exists()) {
				
				try {
					seq = MidiSystem.getSequence(midiFile);
					
					seqr = MidiSystem.getSequencer();
					seqr.open();
					seqr.setSequence(seq);
					
					seqr.start();
					
					
				} catch (InvalidMidiDataException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MidiUnavailableException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public static MidiPlayer getInstance() {
		return (mInstance);
	}
	
	
	public void stop() {
		if (seqr != null) {
			if (seqr.isRunning()) {
				seqr.stop();
			}
		}
	}
	

}
